package setup

import (
	"context"
	"device_mq_handler/configs"
	"device_mq_handler/internal/pkg/instance"
	"errors"
	"gitee.com/lailonghui/vehicle-supervision-framework/pkg/asserts"
	"gitee.com/lailonghui/vehicle-supervision-framework/pkg/vipers"
	"github.com/spf13/pflag"
	"github.com/spf13/viper"
)

var (
	viperEtcdEndpointConfig string = "viper.etcd.endpoints"
	viperEtcdAppPathConfig  string = "viper.etcd.path"
)

// 配置信息初始化
// 设置环境变量 VIPER_ETCD_ENDPOINTS 和 VIPER_ETCD_PATH 覆盖默认的配置中心值
func ConfigInit(ctx context.Context) {

	// 从命令行中获取配置中心默认值
	v := viper.New()
	pflag.String(viperEtcdEndpointConfig, "192.168.3.132:2379", "etcd配置中心地址")
	pflag.String(viperEtcdAppPathConfig, "/dev/dmh/app.yaml", "配置文件在配置中心的路径")
	pflag.Parse()
	err := v.BindPFlags(pflag.CommandLine)
	asserts.Nil(err, errors.New("bind pflag fail"))

	// 从环境变量取值
	err = v.BindEnv(viperEtcdEndpointConfig)
	asserts.Nil(err, errors.New("bind env fail"))
	err = v.BindEnv(viperEtcdAppPathConfig)
	asserts.Nil(err, errors.New("bind env fail"))
	v.AutomaticEnv()

	// 获取配置信息，并且监听配置信息变化
	vipers.ConfigWithEtcd(func(v *viper.Viper) {
		instance.SetViper(v)
		c := configs.Config{}
		err := v.Unmarshal(&c)
		asserts.Nil(err, err)
		instance.SetConfig(&c)
	}, v.GetString(viperEtcdEndpointConfig), v.GetString(viperEtcdAppPathConfig))
}
